#!/bin/bash

# 恢复误删除的Git分支的脚本
# 使用方法: ./recover_branch.sh <分支名>

# 检查参数
if [ $# -ne 1 ]; then
    echo "使用方法: $0 <分支名>"
    exit 1
fi

BRANCH_NAME=$1

echo "正在尝试恢复分支: $BRANCH_NAME"

# 步骤1: 查看reflog
echo "步骤1: 查看reflog以找到被删除分支的最后一次提交"
echo "----------------------------------------"
git reflog | grep -i "$BRANCH_NAME" || echo "未找到与 $BRANCH_NAME 相关的记录"
echo "----------------------------------------"

# 步骤2: 提示用户输入commit hash
echo ""
echo "步骤2: 请输入上面输出中找到的commit hash（如果没有找到，请输入最后一次提交的hash）"
read -p "请输入commit hash: " COMMIT_HASH

# 步骤3: 重新创建分支
echo ""
echo "步骤3: 使用commit hash重新创建分支"
git branch "$BRANCH_NAME" "$COMMIT_HASH"

# 检查分支是否创建成功
if git show-ref --verify --quiet "refs/heads/$BRANCH_NAME"; then
    echo "分支 $BRANCH_NAME 已成功恢复！"
    
    # 步骤4: 询问是否切换到恢复的分支
    read -p "是否切换到恢复的分支？(y/n): " SWITCH_BRANCH
    if [ "$SWITCH_BRANCH" = "y" ] || [ "$SWITCH_BRANCH" = "Y" ]; then
        git checkout "$BRANCH_NAME"
        echo "已切换到分支 $BRANCH_NAME"
    fi
    
    # 步骤5: 询问是否推送到远程
    read -p "是否将恢复的分支推送到远程仓库？(y/n): " PUSH_REMOTE
    if [ "$PUSH_REMOTE" = "y" ] || [ "$PUSH_REMOTE" = "Y" ]; then
        git push -u origin "$BRANCH_NAME"
        echo "分支 $BRANCH_NAME 已推送到远程仓库"
    fi
else
    echo "分支恢复失败，请检查commit hash是否正确"
fi

echo ""
echo "恢复过程完成！" 